package 测试;

import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;

public class RunoobTest  {
    private List synchedList;
    public RunoobTest() {
        //synchronizedList(List list) 方法，获取一个线程安全的 List 实例对象
        synchedList = Collections.synchronizedList(new LinkedList<>());
    }
    //删除列表中的元素
    public String removeElement() throws InterruptedException{
        synchronized (synchedList){
            //列表为空就等待
            while(synchedList.isEmpty())
            {
                System.out.println("列表为空。。。。");
                synchedList.wait();
                System.out.println("等待中。。。。");
            }
            String element = (String) synchedList.remove(0);
            return  element;
        }
    }
    //添加元素到列表
    public void addElement(String element)
    {
        System.out.println("Opening...");
        synchronized (synchedList){
            //添加一个元素，并通知元素已存在
        synchedList.add(element);
        System.out.println("New Element:'"+element+"'");
       synchedList.notifyAll();
    }
        System.out.println("Closing...");
    }

    public static void main(String[] args) {
        final RunoobTest demo=new RunoobTest();
        Runnable runa = () -> {
            try {
                String item=demo.removeElement();
                System.out.println(" "+item);
            }catch (InterruptedException ix)
            {
                System.out.println("Interrupted Exception!");
            }catch (Exception e)
            {
                System.out.println("Exception thrown.");
            }
        };
        Runnable runb= () -> demo.addElement("Hello!");

        try {
            Thread threadA1 = new Thread(runa, "Google");
            threadA1.start();

            Thread.sleep(500);

            Thread threadA2 = new Thread(runa, "Runoob");
            threadA2.start();

            Thread.sleep(500);

            Thread threadB = new Thread(runb, "Taobao");
            threadB.start();

            Thread.sleep(1000);

            threadA1.interrupt();
            threadA2.interrupt();
        } catch (InterruptedException x) {
        }




    }
}


